var selectionRect;
var xmlinstance;
var xamlTemplate;
var itemCount = 0;
var itemHeight = 0;
var trackHeight = 208.1;
var listBoxHeight = 228.5;
var thumbScale;
var itemsContainer;

function setupListbox(sender) {
    // Initialize the scrollbar
    setupScrollbar(sender);
    
    // Get a pointer to the selection rectangle
    selectionRect = sender.findName("selectionRect");
    
    // store a pointer to the Canvas that will contain the items
    itemsContainer = sender.findName("itemsContainer");
}

// Sets the listbox's datasource
function setDataSource(result) {
    var templateInstance;
    
    if (result)
    {
        // Iterate over the data items 
        for (var i = 0; i < result.length; i++)
        {
            // Fill out the template and create a WPF/E element
            templateInstance = instanceTemplate(i, result[i]);
            
            // Position the item in items canvas
            templateInstance["Canvas.Top"] = i * templateInstance.Height;
            itemsContainer.children.insert(0, templateInstance);
            
            // Hook up the new item to eventhandler code
            new listBoxItem(templateInstance, i + 1);
        } 
    }
    
    // Set the listbox's item count;
    itemCount = result.length;
    
    // Set the listbox's item height
    itemHeight = templateInstance.Height;
    
    // Calculate the size of the scroll thumb based on the number of itesm
    calculateScrollThumbSize();
    
    // Call back to notify that items are loaded
    onItemsLoaded();
}

function instanceTemplate(index, templateData) {

    // Databind the template by replacing the placeholders with real data
    var templateInstanceString = xamlTemplate.replaceAll("$0", index + 1);
 
    // Iterate over the proeprties in the data item and fill out the template   
    var i = 0;
    for (var propName in templateData) {
        templateInstanceString = templateInstanceString.replaceAll("$" + (i + 1), templateData[propName]);
        i++;
    }

    // Use createFromXaml to create an element from the string
    var wpfeControl = document.getElementById("wpfeControl1");
    var templateInstance = wpfeControl.createFromXaml(templateInstanceString);
    return templateInstance;
}

function calculateScrollThumbSize() {
    var wpfeControl = document.getElementById("wpfeControl1");
    var thumbBackground = wpfeControl.findName("thumbBackground");
    
    thumbScale = listBoxHeight / (itemHeight * itemCount);
    
    if (thumbScale > 1.0) {
        thumbBackground.height = trackHeight;
    }
    else {
        thumbBackground.height = thumbScale * trackHeight;
    }
}